package com.zju.cst.web.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zju.cst.classification.utils.Similarity;
import com.zju.cst.classification.utils.Split;
import com.zju.cst.spider.domain.News;
import com.zju.cst.spider.mapper.NewsMapper;
import com.zju.cst.spider.utils.DBUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ClassifyController {
	
	private NewsMapper mapper;
	
	private Map<String, Integer> sportsSplit;
	private Map<String, Integer> financeSplit;
	private Map<String, Integer> politicsSplit;
	private Map<String, Integer> travelSplit;

	public ClassifyController(){
		mapper = DBUtils.getSession().getMapper(NewsMapper.class);
		sportsSplit = Split.getWordMapFromClassify("体育");
		financeSplit = Split.getWordMapFromClassify("财经");
		politicsSplit = Split.getWordMapFromClassify("时政");
		travelSplit = Split.getWordMapFromClassify("旅游");

	}

	@RequestMapping("getClassify")
	@ResponseBody
	public JSONArray getClassify(@RequestParam("classify") String classify){
		List<News> list = mapper.selectByClassify(classify);
		return JSONArray.fromObject(list);
	}
	
	
	@RequestMapping("getResult")
	@ResponseBody
	public JSONObject getResult(@RequestParam("content") String content){
		JSONObject object = new JSONObject();
		Map<String, BigDecimal> map = new HashMap<>();
		BigDecimal sports = Similarity.calculate(sportsSplit, Split.getWordMapFromText(content));
		BigDecimal finance = Similarity.calculate(financeSplit, Split.getWordMapFromText(content));
		BigDecimal politics = Similarity.calculate(politicsSplit, Split.getWordMapFromText(content));
		BigDecimal travel = Similarity.calculate(travelSplit, Split.getWordMapFromText(content));
		object.put("sports", sports);
		map.put("体育", sports);
		object.put("finance", finance);
		map.put("财经", finance);
		object.put("politics", politics);
		map.put("时政", politics);
		object.put("travel", travel);
		map.put("旅游", travel);
		
		object.put("classify", getMax(map));
		return object;
	}
	
	public static String getMax(Map<String, BigDecimal> map){
		String maxString = null;
		BigDecimal maxValue = new BigDecimal(0);
		for(Map.Entry<String, BigDecimal> entry : map.entrySet()){
			if(entry.getValue().compareTo(maxValue) > 0) {
				maxValue = entry.getValue();
				maxString = entry.getKey();
			}
		}
		return maxString;
	}
}
